import React, { Component } from 'react';
import {
    Text,
    View,
    TextInput,
    TouchableOpacity,
} from 'react-native';
//加载模块样式
import { Loginstyles as styles } from '../../../../styles'
import Icon from 'react-native-vector-icons/Ionicons';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
// 获取当前设备的宽度
const Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

import { NavigationActions } from 'react-navigation';

import { myAlert } from '../../../util/compatible'
import { loginForEmail, loginForToken } from '../../../actions/userAction'
import stirageUtil from '../../../util/AsyncStorageUtil'
import { header,header2,header3} from '../../../util/fetch'

class Account extends Component {
    
    username = false;
    password = false;

    constructor(props){
        super(props);
        this.state = ({
            //密码显示与隐藏  true为显示 false为隐藏
            show: true,
            //登录按钮是否可用
            isOk: false,
            //是否等待
            isloading: false
        });
    }

    //显示密码时,输入框光标消失
    _onPress() {
        this.refs.password.blur();
    }

    goLogin() {
        if (this.state.isOk) {
            this.setState({ isloading: true })
            this.setState({ isOk: false })
            this.props.actions.loginForEmail({
                username: this.refs.username._lastNativeText,
                password: this.refs.password._lastNativeText
            });
        }
    }

    isOKN(val){
        if(val.length>2){
            this.username = true
        }else{
            this.username = false
        }
        this.isOk()
    }

    isOk(){
        if(this.username && this.password){
                this.setState({isOk:true})
            }else{
                this.setState({isOk:false})
        }
    }

    isOKP(val){
        if(val.length>2){
            this.password = true
        }else{
            this.password = false
        }
        this.isOk()
    }

    componentDidUpdate() {
        if(this.props.loginData.statusText=="err"&&this.state.isloading==true){
            myAlert("网络连接失败！")
            this.setState({isOk:true,isloading:false})
        }
    }

    componentWillReceiveProps(nextProps) {
        const { data } = nextProps.loginData
        if (data.msg != "") {
            //登录成功
            if (data.msg == "ok") {
                stirageUtil.save("userType", data.userType).then(()=>{
                    //保存token
                    stirageUtil.save("accountToken", data.token).then(() => {
                        header.accessToken = data.token
                        header2.accessToken = data.token
                        header3.accessToken = data.token
                        this.passing()
                    });
                })
            } else {
                //失败弹出消息
                myAlert(data.msg)
            }
            this.setState({ isOk: true, isloading: false })
        }
    }

    passing() {
        resetAction = NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({ routeName: 'App' })//要跳转到的页面名字
            ]
        });
        this.props.navigation.dispatch(resetAction);
    }


    render() {
        return (
            <View style={styles.container}>
                {/** 输入框容器 */}
                <View style={[styles.textInputContianer, { width: width * 0.85 }]}>

                    {/** 用户名输入框 */}
                    <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                        <Icon
                            name={'md-person'}
                            size={22}
                            color={'#ffffff'} style={styles.ImageStyle} />
                        {/* <Image source={require('../../../img/Login/u1699.png')} style={styles.ImageStyle} /> */}
                        <TextInput
                            ref="username"
                            placeholder="请输入用户名"
                            clearButtonMode="always"
                            underlineColorAndroid="transparent"
                            style={[styles.textInputStylePhoneNum, { width: width * 0.85 }]}
                            onChangeText={this.isOKN.bind(this)}>
                        </TextInput>
                    </View>
                    {/** 分割线 */}
                    <View style={styles.dividingLine} />
                    <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                        <Icon
                            name={'md-unlock'}
                            size={22}
                            color={'#ffffff'} style={styles.ImageStyle} />

                        {/** 密码输入框 */}
                        <TextInput
                            ref="password"
                            placeholder="请输入密码"
                            style={[styles.textInputStylePWD, { width: width * 0.85 }]}
                            password={true}
                            //输入为密码隐藏样式
                            secureTextEntry={this.state.show}
                            clearButtonMode="always"
                            underlineColorAndroid="transparent"
                            onChangeText={this.isOKP.bind(this)}>
                        </TextInput>
                        {/* 密码框显示或隐藏密码 */}
                        <TouchableOpacity
                            style={styles.eysStyle}
                            onPressIn={() => { [this.setState({ show: !this.state.show }), this._onPress()] }}
                            onPressOut={() => { this.setState({ show: !this.state.show }) }}>
                            <Icon
                                name={'md-eye'}
                                size={22}
                                color={'#ffffff'} />
                        </TouchableOpacity>

                    </View>
                </View>
                {/*登录按钮*/}
                <View>
                    <TouchableOpacity activeOpacity={1} style={this.state.isOk ? [styles.loginBtnStyle, { width: width * 0.85 ,
                    elevation: 3,
                    shadowColor: 'black',
                    shadowOpacity: 1,
                    shadowRadius: 5}] : [styles.loginBtnStyle, { backgroundColor: "#aeaeae", width: width * 0.85,
                    elevation: 3,
                    shadowColor: 'black',
                    shadowOpacity: 1,
                    shadowRadius: 5 }]}
                        underlayColor={this.state.isOk ? "#3D9CCC" : "#aeaeae"} onPress={this.goLogin.bind(this)}>
                        <Text style={{ color: '#fff', fontSize: 15,fontFamily:"msyh" }}>
                            {this.state.isloading ? "等  待" : "登  录"}
                        </Text>
                    </TouchableOpacity>
                </View>
                {/*默认设置*/}
                <TouchableOpacity style={[styles.forgetpasStyle, { width: width * 0.8 }]}
                onPress={() => { this.props.navigation.navigate('Validate') }}>
                    {/*左边*/}
                    <Text style={{ color: '#cccccc',fontFamily:"msyh",fontSize:12 }}>忘记密码?</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

//组合action
var actions = {
    loginForEmail, loginForToken
}
//连接state到props
const mapStateToProps = state => {
    return {
        loginData: state.loginEmailReducer
    }
}
//连接action
const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators(actions, dispatch)
    }
}
//导出组合好的组件(组合后状态改变重新渲染组合组件的页面)
export default connect(
    mapStateToProps, mapDispatchToProps
)(Account);
